package org.i1510.common.utils.baidu;
import java.util.ArrayList;

import org.apache.http.client.utils.URLEncodedUtils;
import org.apache.http.message.BasicNameValuePair;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
 
/**
 * @author Gao Yudong (gyd@nbicc.com)
 * @date 2015-2-26
 */
public class PlaceSuggestion {
    private static final String TAG = PlaceSuggestion.class.getName();
 
    private String query = null;
 
    public void setQuery(String query) {
        this.query = query;
    }
 
    @SuppressWarnings({"rawtypes", "unchecked"})
    private String createURI() {
        ArrayList params = new ArrayList();
        params.add(new BasicNameValuePair("ak", Constant.BAIDU_AK));
        params.add(new BasicNameValuePair("output", "json"));
        params.add(new BasicNameValuePair("query", query));
        params.add(new BasicNameValuePair("region", "全国"));
        return Constant.PLACE_SUGGESTION_URL + "?"
                + URLEncodedUtils.format(params, Constant.CHARSET);
    }
     
    public ArrayList<SuggestBean> execute() {
        ArrayList<SuggestBean> suggestList = new ArrayList<SuggestBean>();
        String response = HttpUtils.doGet(createURI());
        JSONObject obj = JSON.parseObject(response);
        if (obj.getIntValue("status") == 0) {
            JSONArray suggestArr = obj.getJSONArray("result");
            for (int i = 0; i < suggestArr.size(); i++) {
                JSONObject sgtObj = (JSONObject) suggestArr.get(i);
                SuggestBean poi = JSON.parseObject(sgtObj.toJSONString(),
                        SuggestBean.class);
                suggestList.add(poi);
            }
        }
        return suggestList;
    }
     
    public static void main(String[] args) {
        PlaceSuggestion search = new PlaceSuggestion();
        search.setQuery("宁波保利影城(天一店)");
        search.setQuery("厦门湖里万达");
        ArrayList<SuggestBean> list = search.execute();
        Print.pln(TAG, list);
    }
}